from flask import Flask, render_template, request, session, redirect, url_for
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
import graphgenerator


# Init ####################################################################
app = Flask(__name__)

app.secret_key = b'\x7f\x0e\x9b\xd8\xd5\xd8\x8f\xfa\xac\x1a\x026\xfe\xdf\xa2r'

app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://dukalee:mima@localhost/digdb'

Session(app)
db = SQLAlchemy(app)


# Models ##################################################################
class Digusers(db.Model):
    username = db.Column(db.String(30), primary_key=True)
    password = db.Column(db.String(30))
    status = False


class Itemsummary(db.Model):
    id = db.Column(db.Integer)
    item = db.Column(db.String(100), primary_key=True)
    level = db.Column(db.Integer)


# HTML Pages ##############################################################
pages = ['hello', 'index', 'main_page', 'graph_page']  # HTML Pages, also add pages in every return render_template


# Routes ##################################################################
@app.route("/")
def default():
    return redirect(url_for('hello'))


@app.route('/hello')
def hello():
    if session.get("user") is None:
        session["user"] = Digusers()
    return render_template("hello.html", pages=pages, user=session["user"])


@app.route("/index")
def index():
    items = Itemsummary.query.all()
    return render_template("index.html", pages=pages, items=items, user=session["user"])


@app.route("/main_page", methods=["GET", "POST"])
def main_page():
    main_pic = "pic/tsbavatar.jpg"
    if session.get("fruits") is None:
        session["fruits"] = []
    if request.method == "POST":
        fruit = request.form.get("fruit")
        session["fruits"].append(fruit)

    return render_template("main_page.html", pages=pages, fruits=session["fruits"], main_pic=main_pic,
                           user=session["user"])


@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']
    c_username = Digusers.query.filter_by(username=username).first()
    c_password = Digusers.query.filter_by(username=username).first()
    if c_username and username == c_username.username:
        if c_password and password == c_password.password:
            session['user'].status = True
            session['user'].username = username
            graphgenerator.clear_graph(session['user'].username)
    return redirect(url_for('index'))


@app.route('/logout')
def logout():
    session.pop('user', None)
    return redirect(url_for('hello'))


'''
@app.route('/graph')
def graph():
    if session['user'].status:
        skins = graphgenerator.get_skins()
        dates = graphgenerator.get_dates()
        return render_template('graph.html', pages=pages, user=session['user'], skins=skins, dates=dates)
    else:
        return redirect(url_for('hello'))
'''


@app.route('/graph_page', methods=['GET', 'POST'])
def graph_page():
    if session['user'].status:
        skins = graphgenerator.get_skins()
        dates = graphgenerator.get_dates()
        if request.method == 'POST':
            buff_id = request.form['buff_id']
            date1 = request.form['date1']
            date2 = request.form['date2']
            graphgenerator.generate_graph(buff_id, date1, date2, session['user'].username)
        return render_template('user_graph/graph{}.html'.format(session['user'].username), pages=pages,
                               user=session['user'], skins=skins, dates=dates)
    else:
        return redirect(url_for('hello'))


@app.route('/clear_graph')
def clear_graph():
    if session['user'].status:
        graphgenerator.clear_graph(session['user'].username)
        return redirect(url_for('graph_page'))
    else:
        return redirect(url_for('hello'))
